package cn.java75.sp.service;

import cn.java75.sp.dao.AdminDao;
import cn.java75.sp.entity.Admin;
import cn.java75.sp.entity.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author oldliu
 * @since 1.0
 */
@Service
public class LoginServiceImpl implements UserDetailsService {

    @Autowired
    private AdminDao adminDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Admin admin = adminDao.get(s);
        if(admin==null)
            throw  new UsernameNotFoundException("用户名不存在");

        LoginUser u= new LoginUser(admin,adminDao.getRightsByUser(admin.getRoleid()));

        ServletRequestAttributes attributes = (ServletRequestAttributes)(RequestContextHolder.getRequestAttributes());
        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();

        String uuid= UUID.randomUUID().toString();

        response.setHeader("token",uuid);
        request.setAttribute("token",uuid);
        this.redisTemplate.opsForValue().set(uuid,u,5, TimeUnit.HOURS);
        return u;
    }
}
